<template>
  <div>
    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="连接1" name="first"></el-tab-pane>
      <el-tab-pane label="连接2" name="second"></el-tab-pane>
      <el-tab-pane label="连接3" name="third"></el-tab-pane>
    </el-tabs>
    <!-- 动态加载子组件 -->
    <keep-alive>
      <component :is="currentComponent" />
    </keep-alive>
  </div>
</template>

<script>
import PointToPoint from '@/views/websocketTest/socket1';
import GroupChat from '@/views/websocketTest/socket2';
import SelfChat from '@/views/websocketTest/socket3';
export default {
  components: {
    PointToPoint,
    GroupChat,
    SelfChat,
  },
  data() {
    return {
      url: "ws://127.0.0.1:8080/websocket/message",
      message: "",
      text_content: "",
      ws: null,
      activeName: "first",
    };
  },
  computed: {
    // 根据 activeName 返回对应的组件
    currentComponent() {
      switch (this.activeName) {
        case 'first':
          return 'PointToPoint';
        case 'second':
          return 'GroupChat';
        case 'third':
          return 'SelfChat';
        default:
          return null;
      }
    },
  },
  methods: {
    join() {
      const wsuri = this.url;
      this.ws = new WebSocket(wsuri);
      const self = this;
      this.ws.onopen = function (event) {
        self.text_content = self.text_content + "已经打开连接!" + "\n";
        console.log(self.text_content)
      };
      this.ws.onmessage = function (event) {
        console.log(event)
        self.text_content = event.data + "\n";
        console.log(self.text_content)
      };
      this.ws.onclose = function (event) {
        self.text_content = self.text_content + "已经关闭连接!" + "\n";
        console.log(self.text_content)
      };
    },
    exit() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
    send() {
      if (this.ws) {
        this.ws.send(this.message);
      } else {
        this.$alert('未连接到服务器！', 'websocket', {
          confirmButtonText: '确定',
          type: 'warning',
        });
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },

  },
};
</script>
